package com.etc.traval.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.traval.biz.OrderBiz;
import com.etc.traval.biz.RoomBiz;
import com.etc.traval.biz.SellerBiz;
import com.etc.traval.biz.UserBiz;
import com.etc.traval.bizimpl.OrderBizImpl;
import com.etc.traval.bizimpl.RoomBizImpl;
import com.etc.traval.bizimpl.SellerBizImpl;
import com.etc.traval.bizimpl.UserBizImpl;
import com.etc.travel.entity.Order;
import com.etc.travel.entity.Room;
import com.etc.travel.entity.Seller;
import com.etc.travel.entity.User;
import com.google.gson.Gson;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
    	String flag=null;
    	if(request.getParameter("flag")!=null){
    		flag=request.getParameter("flag");
    	}
    	if (flag.equals("add")) {
    		UserBiz ub=new UserBizImpl();
    		SellerBiz sb=new SellerBizImpl();
    		RoomBiz rb=new RoomBizImpl();
    		OrderBiz ob=new OrderBizImpl();
    		String timein=request.getParameter("timein")+" 00:00:00";
    		String timeout=request.getParameter("timeout")+" 00:00:00";
    		String roomtype=request.getParameter("roomtype");
    		int sellerid=Integer.valueOf( request.getParameter("seller"));
    		int userid=Integer.valueOf( request.getParameter("user"));
    		User user=ub.queryUserById(userid);
    		Seller seller=sb.selectSellerById(sellerid);
    		String system="可预订";
    		List<Room> list=rb.queryBySellerTypeSystem(seller, roomtype, system);
    		//Room room=list.get(0);
    		if(list.size()==0){
    			out.println("<script>alert('请重新选择房间');location.href='SellerServlet?flag=hotelinfo&hotelid="+sellerid+"'</script>");	
    		}else{
    			Double ordermoney=list.get(0).getRoom_money();
        		
        	    //获取系统当前时间
        		Date day1=new Date();
        		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Timestamp tp=Timestamp.valueOf(format.format(day1)) ;
                long order_time=0;
                long order_endtime=0;
    			try {
    				order_time = format.parse(timein).getTime();
    				order_endtime=format.parse(timeout).getTime();
    			} catch (ParseException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
               
    		    String state="进行中";
    		    long day=(order_endtime-order_time)/(1000*60*60*24);
                Order order=new Order();
                order.setOrder_days((int)day);
                order.setOrder_endtime ( Timestamp.valueOf(timeout));
                order.setOrder_money(ordermoney);
                order.setOrder_room(list.get(0));
    		    order.setOrder_seller(seller);
    		    order.setOrder_state(state);
    		    order.setOrder_time(tp);
    		    order.setOrder_user(user);
    		    if(user.getUser_money()>=list.get(0).getRoom_money()){
    		    	
    		    if (ob.addOrder(order)) {
    		    	rb.updateRoomById("满房", list.get(0).getRoom_id());
    		        ub.reduceUserMoneyById(userid,list.get(0).getRoom_money());
    		        HttpSession session1 =request.getSession();
              		User user1 = (User) session1.getAttribute("user");
					double oldmoney=user1.getUser_money();
					user.setUser_money(oldmoney-order.getOrder_money());
					session1.setAttribute("user", user);  
					request.getSession().setAttribute("order", order);
    		        sb.rechargeMoneyById(list.get(0).getRoom_money(), sellerid);
    		    	out.println("<script>alert('下单成功');location.href='ordersuccess.jsp'</script>");
    			}
    		    }else{
    		    	out.println("<script>alert('您的余额不足。请先充值');location.href='hotelin.jsp'</script>");	
    		    }
    		}
    		out.flush();
			out.close();
    	}else if(flag.equals("order")){
    		OrderBiz biz=new OrderBizImpl();
    		SellerBiz sbiz=new SellerBizImpl();
			List<Order> list = biz.queryOrderBySeller(sbiz.selectSellerById(Integer.valueOf(request.getParameter("sellerid"))));
			
			Gson gson = new Gson();
			String jsonString = gson.toJson(list);
			response.setContentType("text/html;charset=utf-8");
			
			out.print(jsonString);
			out.flush();
			out.close();
    		
    		
    	}
    	else if(flag.equals("update")){
    		OrderBiz biz=new OrderBizImpl();
    		RoomBiz biz1=new RoomBizImpl();
    		//HttpSession session =request.getSession();
    		int orderid=Integer.valueOf(request.getParameter("orderid"));
    		Order order=biz.queryById(orderid);
    		String state=request.getParameter("state");
    		if( biz.updateStateById(state, orderid)){
                biz1.updateRoomById("可预订", order.getOrder_room().getRoom_id() );
    			out.println("<script>alert('修改成功');location.href='SellerManage.jsp'</script>");
    		}else{
    			out.println("<script>alert('修改失败');location.href='SellerManage.jsp'</script>");	
    		}
			out.flush();
			out.close();
    		
    	}
			
	}

}
